﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AlexandriaPressUserBusinessLayer;
using AlexandriaPressUserObject;
using MailSender;

namespace AlexandriaPressWebsite.MasterPages.UserPages
{
    public partial class Checkout : System.Web.UI.Page
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            UserBusinsessLayer business = new UserBusinsessLayer();
            string _UserType = business.getUserType(HttpContext.Current.User.Identity.Name);
            if (_UserType == "Type_Buyer" || _UserType == "Type_Admin" || _UserType == "Type_ProofReader" || _UserType == "Type_Author")
            {

            }
            else
            {
                Response.Redirect("~/MasterPages/ErrorPage.aspx");
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["blocked"] != null)
            {
                Session.RemoveAll();
                Response.Redirect("~/MasterPages/MainPage.aspx");
            }

            if (Session["userID"] == null)
            {
                Response.Redirect("~/MasterPages/UserPages/LoginPage.aspx");  
            }


            Button signUpButton = (Button)this.Master.FindControl("signUpButton");
            Button logInButton = (Button)this.Master.FindControl("logInButton");
            Button TermsButton = (Button)this.Master.FindControl("TermsButton");
            Button myAccountButton = (Button)this.Master.FindControl("myAccountButton");
            Button myTransactionsButton = (Button)this.Master.FindControl("myTransactionsButton");
            Button mostPopularButton = (Button)this.Master.FindControl("mostPopularButton");
            Button searchButton = (Button)this.Master.FindControl("searchButton");
            Button reportsButton = (Button)this.Master.FindControl("reportsButton");
      
            Button authorAppButton = (Button)this.Master.FindControl("authorAppButton");
            Button manageUsersButton = (Button)this.Master.FindControl("manageUsersButton");
            Button manageAuthorsButton = (Button)this.Master.FindControl("manageAuthorsButton");
            Button manageProofReadersButton = (Button)this.Master.FindControl("manageProofReadersButton");
            Button searchDraftsButton = (Button)this.Master.FindControl("searchDraftsButton");
            Button submitDraftButton = (Button)this.Master.FindControl("submitDraftButton");
            Button searchBooksButton = (Button)this.Master.FindControl("searchBooksButton");
            Button authorApplicationsAdminButton = (Button)this.Master.FindControl("authorApplicationsAdminButton");
            Button viewDraftsProofreaderButton = (Button)this.Master.FindControl("viewDraftsProofreaderButton");
            Button proofreaderConsoleButton = (Button)this.Master.FindControl("proofreaderConsoleButton");


            signUpButton.Visible = false;
            logInButton.Visible = false;
            TermsButton.Visible = false;
            myAccountButton.Visible = false;
            myTransactionsButton.Visible = false; 
            mostPopularButton.Visible = false; 
            searchButton.Visible = false;
            reportsButton.Visible = false;
            authorAppButton.Visible = false;
            manageUsersButton.Visible = false;
            manageAuthorsButton.Visible = false;
            manageProofReadersButton.Visible = false; 
            searchDraftsButton.Visible = false; 
            submitDraftButton.Visible = false;
            searchBooksButton.Visible = false; 
            authorApplicationsAdminButton.Visible = false;
            viewDraftsProofreaderButton.Visible = false;
            proofreaderConsoleButton.Visible = false;
           
            decimal totPrice = 0;
            foreach (OrderItems item in (List<OrderItems>)Session["orders"])
            {
                totPrice += (item.Quantity * item.Price);
            }
            headerLabel.Text = "Checkout - Total Price: " + Convert.ToString(totPrice) + " peso(s)";
        }

        protected void checkoutSubmitBtn_Click(object sender, EventArgs e)
        {
            bool creditCardsMatch = UserBusinsessLayer.validateCreditCard(cardTypeDropDown.SelectedItem.Value, cardNumBox.Text.Trim(), codeBox.Text.Trim(), expirationMonth.Value, expirationYear.Value, Convert.ToInt32(Session["userID"]));
            bool isDownload = false;
            List<int> itemsForDownload = new List<int>();
            int transID = 0;
            decimal money = 0;
            if (creditCardsMatch == true)
            {
                string address = "";
                if (deliveryTypeList.SelectedItem.Value == "Send to Shipping Address")
                {
                    if (newAddressCheck.Checked == true)
                    {
                        string countrySelected = Request.Form["Country"];
                        address = saBox.Text.Trim() + " " + cOTBox.Text.Trim() + " " + sOPBox.Text.Trim() + zipBox.Text.Trim() + " " + countrySelected;
                    }
                    else
                    {
                        address = "default";
                    }
                }
                else
                {
                    isDownload = true;
                }

                if (UserBusinsessLayer.checkOut(Convert.ToInt32(Session["userID"]), address, (List<OrderItems>)Session["orders"], ref transID) == "Transaction failed")
                {
                    Response.Redirect("~/MasterPages/TransactionErrorPage.aspx");
                }

                string body = "<html><body>Thank you for using our service!<br/><br/>This will serve as the official receipt for your transaction. You may print this for your records.<br/><br/>";
                body += "Transaction ID: " + Convert.ToString(transID) + "<br/>";
                body += "Transaction Timestamp: " + Convert.ToString(DateTime.Now) + "<br/><br/><br/>";
                body += "<table><th><td>Title</td><td>Price</td><td>Quantity</td></th>";
                foreach (OrderItems item in (List<OrderItems>)Session["orders"])
                {
                    money += (item.Quantity * item.Price);
                    body += "<tr>";
                    body += "<td>" + item.Title + "</td><td>" + item.Quantity + "</td><td>" + item.Price + "</td>";
                    body += "</tr>";
                }
                body += "</table><br/>Total Price: " + Convert.ToString(money) + "<body><html>";


                UserBusinsessLayer user = new UserBusinsessLayer();
                EmailNotification.AdminMail("admin@alexandria.com", user.getUser(HttpContext.Current.User.Identity.Name).Email, "", "", "Confirmation of Transaction", body);



                if (isDownload)
                {
                    Response.Redirect("~/MasterPages/UserPages/UserDownloadPage.aspx");
                }
                else
                {
                    itemsForDownload.Clear();
                    Response.Redirect("~/MasterPages/DeliveryConfirmationPage.aspx");
                }
            }
            else
            {
                Response.Redirect("~/MasterPages/TransactionErrorPage.aspx");
            }
        }

        protected void newAddressCheck_Handler(object sender, EventArgs e)
        {
            if (newAddressCheck.Checked == true)
            {
                streetAddressLabel.Visible = true;
                saBox.Visible = true;
                cityOrTownLabel.Visible = true;
                cOTBox.Visible = true;
                stateOrProvinceLabel.Visible = true;
                sOPBox.Visible = true;
                zipLabel.Visible = true;
                zipBox.Visible = true;
                countryLabel.Visible = true;
                country.Visible = true;
                RequiredFieldValidator1.Enabled = true;
                RequiredFieldValidator2.Enabled = true;
                RequiredFieldValidator3.Enabled = true;
                RequiredFieldValidator1.Visible = true;
                RequiredFieldValidator2.Visible = true;
                RequiredFieldValidator3.Visible = true;
            }
            else
            {
                streetAddressLabel.Visible = false;
                saBox.Visible = false;
                cityOrTownLabel.Visible = false;
                cOTBox.Visible = false;
                stateOrProvinceLabel.Visible = false;
                sOPBox.Visible = false;
                zipLabel.Visible = false;
                zipBox.Visible = false;
                countryLabel.Visible = false;
                country.Visible = false;
                RequiredFieldValidator1.Enabled = false;
                RequiredFieldValidator2.Enabled = false;
                RequiredFieldValidator3.Enabled = false;
                RequiredFieldValidator1.Visible = false;
                RequiredFieldValidator2.Visible = false;
                RequiredFieldValidator3.Visible = false;
            }
        }

        protected void deliveryType_selectedIndexChanged(object sender, EventArgs e)
        {
            if (deliveryTypeList.SelectedItem.Value == "Download")
            {
                newAddressCheck.Visible = false;
                streetAddressLabel.Visible = false;
                saBox.Visible = false;
                cityOrTownLabel.Visible = false;
                cOTBox.Visible = false;
                stateOrProvinceLabel.Visible = false;
                sOPBox.Visible = false;
                zipLabel.Visible = false;
                zipBox.Visible = false;
                countryLabel.Visible = false;
                country.Visible = false;
                RequiredFieldValidator1.Enabled = false;
                RequiredFieldValidator2.Enabled = false;
                RequiredFieldValidator3.Enabled = false;
                RequiredFieldValidator1.Visible = false;
                RequiredFieldValidator2.Visible = false;
                RequiredFieldValidator3.Visible = false;
            }
            else
            {
                newAddressCheck.Visible = true;
            }    
        }

        protected void cancelButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/MasterPages/MainPage.aspx");
        }
    }
}
